package com.wxwx.flutter_alibc;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.alibclogin.AlibcLogin;
import com.alibaba.alibcprotocol.param.AlibcBizParams;
import com.alibaba.alibcprotocol.param.AlibcDegradeType;
import com.alibaba.alibcprotocol.param.AlibcShowParams;
import com.alibaba.alibcprotocol.param.AlibcTaokeParams;
import com.alibaba.alibcprotocol.param.OpenType;
import com.alibaba.ariver.kernel.common.utils.JSONUtils;
import com.alibaba.baichuan.trade.common.AlibcTradeCommon;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baichuan.nb_trade.AlibcTrade;
import com.baichuan.nb_trade.auth.TopAuth;
import com.baichuan.nb_trade.callback.AlibcTradeCallback;
import com.baichuan.nb_trade.callback.AuthCallback;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodCall;

public class CustomActivity extends AppCompatActivity {

    private int mResumeIndex = 0;

    private static MethodChannel.Result mResult;
    private static MethodCall mMethodCall;

    public static void setCallBack(MethodChannel.Result result, MethodCall methodCall) {
        mResult = result;
        mMethodCall = methodCall;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.top_activity);
        String method = getIntent().getStringExtra("method");
        switch (method) {
            case "authLogin":
                authLogin(mResult);
                break;
            case "openDetail":
//                openDetail(mMethodCall, mResult);
                break;
        }
        this.setFinishOnTouchOutside(true);
    }

    @Override
    protected void onResume() {
        mResumeIndex++;
        super.onResume();
        if (mResumeIndex > 1) {
            finish();
        }
    }

    /**
     * 开启淘宝商品对应页
     *
     * @param call
     * @param result
     */
//    public synchronized void openDetail(MethodCall call, MethodChannel.Result result) {
//        Log.d("substring", "openDetail");
//        AlibcBizParams alibcBizParams = new AlibcBizParams();
//        JSONObject object = JSONUtils.parseObject(call.argument("json").toString());
//
//        Log.d("substring", call.argument("json").toString());
//
//        // 其他业务参数
//        HashMap<String, String> extMap = new HashMap<>();
//        // 设置直播间id（此时不要设置商品id）
//        extMap.put("id", object.getString("id"));
//        alibcBizParams.setId(object.getString("id"));
//        alibcBizParams.setExtParams(extMap);
//        AlibcShowParams showParams = new AlibcShowParams();
//        showParams.setOpenType(OpenType.Auto);
//        showParams.setClientType("taobao");
//        showParams.setBackUrl("szmf://");
//        showParams.setDegradeType(AlibcDegradeType.H5);
//        AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams(object.getString("pid"));
//        alibcTaokeParams.pid = object.getString("pid");
//        String url = object.getString("url");
//        alibcTaokeParams.materialSourceUrl = url;
//        String relationId = object.getString("relationId");
//        if (!TextUtils.isEmpty(relationId)) {
//            alibcTaokeParams.relationId = relationId;
//        }
//        Map<String, String> trackParams = new HashMap<>(16);
//        if (!TextUtils.isEmpty(url)) {
//            if (!url.contains("http")) {
//                url = url.replace("//uland", "http://uland");
//            }
//            AlibcTrade.openByUrl(CustomActivity.this, url, showParams, alibcTaokeParams, trackParams, new AlibcTradeCallback() {
//                @Override
//                public void onSuccess(int i) {
//                    Log.d("substring", "open success: code = " + i);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            finish();
//                            overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
//                        }
//                    });
//                }
//
//                @Override
//                public void onFailure(int i, String s) {
//                    Log.d("substring", "open fail: code = " + i + ", msg = " + s);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            finish();
//                            overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
//                        }
//                    });
//                }
//            });
//        } else {
//            String codeDetail = "suite://bc.suite.basic/bc.template.detail";
//            AlibcTrade.openByCode(CustomActivity.this, codeDetail, alibcBizParams, showParams,
//                    alibcTaokeParams, trackParams, new AlibcTradeCallback() {
//                        @Override
//                        public void onSuccess(int i) {
//                            Log.d("substring", "open success: code = " + i);
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    finish();
//                                    overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onFailure(int i, String s) {
//                            Log.d("substring", "open fail: code = " + i + ", msg = " + s);
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    finish();
//                                    overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
//                                }
//                            });
//                        }
//                    });
//        }
//    }

    /**
     * 申请淘宝授权登录
     *
     * @param result
     */
    public void authLogin(final MethodChannel.Result result) {
        TopAuth.showAuthDialog(CustomActivity.this, R.mipmap.ic_launcher, "魔方黑卡", new AuthCallback() {
            @Override
            public void onSuccess(String token, String s) {
                Map<String, Object> map = AlibcLogin.getInstance().getUserInfo();
                JSONObject mJSONObject = new JSONObject();
                mJSONObject.put("accessToken", token);
                mJSONObject.put("nick", map.get("nick"));
                mJSONObject.put("openId", map.get("userId"));
                mJSONObject.put("utdid", AlibcTradeCommon.getUtdid());
                mJSONObject.put("expiresIn", s);
                result.success(JSON.toJSONString(mJSONObject));
                Log.d("substring", "授权成功 " + JSON.toJSONString(mJSONObject));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
                    }
                });
            }

            @Override
            public void onError(String s, String s1) {
                result.error(s, s1, null);
                Log.d("substring", "授权失败 " + s + s1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        overridePendingTransition(R.anim.triver_fade_in, R.anim.triver_fade_out);
                    }
                });
            }
        });
    }

    @Override
    public void onBackPressed() {
        Log.d("substring", "onBackPressed");
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        mResult = null;
        super.onDestroy();
    }
}
